from django.http import HttpResponse
from django.shortcuts import render, render_to_response, redirect
from django.template import loader
from blog.models import Pub
from blog.models import Blog
from django.core.exceptions import ObjectDoesNotExist
from datetime import datetime

# Create your views here.
# from django.conf.urls import url

# from django.http import HttpResponse

# 个人网站首页


def index(request):
    return render(request, 'index.html')

# 登录注册模块


def login(request):
    username = request.POST['username']
    try:
        user = Pub.objects.get(name=username)
        if user.password == request.POST['password']:
            request.session.flush()
            request.session['has_logged'] = True
            response = redirect('/publish/')
            response.set_cookie("username", username, 3600)
            return response
        else:
            return HttpResponse("password error")
    except ObjectDoesNotExist:
        return HttpResponse("you are logged failed")


def register(request):
    username = request.POST['username']
    try:
        Pub.objects.get(name=username)
        return HttpResponse('用户已存在')
    except ObjectDoesNotExist:
        u = Pub()
        u.name = username
        u.password = request.POST["password"]
        u.email = request.POST['email']
        u.save()
        return render(request, 'index.html')

# 文章发布界面


def publish(request):
    if request.method == "GET":
        return render(request, 'publish.html')
    elif request.method == "POST":
        u = Blog()
        v = Pub()
        v.name = request.COOKIES['username']
        u.name = v
        u.title = request.POST['articletitle']
        u.body = request.POST['body']
        u.timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        u.save()
        return redirect('/blog/')
    else:
        return HttpResponse('发布失败')

# 登录注册界面


def blogin(request):
    if request.method == "GET":
        return render_to_response('blogin.html')
    elif request.method == "POST":
        if "login" in request.POST:
            return login(request)
        if "register" in request.POST:
            return register(request)


def blogarticle(request):
    article = Blog.objects.all()
    t = loader.get_template('blogarticle.html')
    return HttpResponse(t.render({'articles': article}))
